package com.lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.Builder;
import lombok.Data;

public class TestListToMap {

	public static void main(String[] args) {
		List<User> userList = new ArrayList<User>();
		for (int i = 0;i<10;i++) {
			User user = User.builder().code("code"+i)
					.name("name"+i)
					.age(i)
					.gped(i % 3)
					.sex(i % 2 == 0 ? "男":"女").build();
//			if(i%9 == 1) {
//				user.setSex(null);
//			}
			userList.add(user);
		}
		
		System.out.println(
				userList.stream().filter(j->j.getSex().equals("男")).count()
				);
		
		Map<String, List<User>> map = userList.stream().collect(Collectors.groupingBy(User::getSex));
		System.out.println(map);
		
		
		
		Map<Optional<String>, List<User>> map2 = userList.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getSex())));
		System.out.println(map2);
		
		// List 转map
		  /**
         * List -> Map
         * 需要注意的是：
         * toMap 如果集合对象有重复的key，会报错Duplicate key ....
         *  user1,user2的id都为1。
         *  可以用 (k1,k2)->k1 来设置，如果有重复的key,则保留key1,舍弃key2
         */
		Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getCode, a -> a,(k1,k2)->k1));
		System.out.println(userMap);
		
		userList.stream().forEach(a -> a.setDelFlag(0));
		
		List<User> filterList = userList.stream().filter(x -> x.getGped() == 1).filter(x -> x.getSex().equals("女")).toList();
		System.out.println(filterList);
		System.out.println(userList);
		
		userList.add(User.builder().code("codeX")
				.name("nameX")
				.age(null)
				.sex("男女").build());
		Map<String, Integer> studentMap = userList.stream()
				.filter(e->e.getAge()!=null)
				.collect(Collectors.toMap(User::getName, User::getAge));
		System.out.println(studentMap);
		
		//字符串分隔符连接
//		String joinName = userList.stream().map(User::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
//		System.out.println(joinName);
//		// .查询总数
//		Long count = userList.stream().filter(x->x.getGped() == 1).collect(Collectors.counting()); 
//		System.out.println(count);
//		
//		Set<String> strSet = userList.stream().map(User::getName).collect(Collectors.toSet());
//		System.out.println(strSet);
//		joinName = strSet.stream().collect(Collectors.joining(",")); // (aa,bb,cc)
//		System.out.println(joinName);
		
		

	}

}
@Data
@Builder
class User {
	private String code;

	private String name;
	private Integer age;
	private String sex;
	private Integer gped;
	private Integer delFlag;
	
}
